<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
loop 1
</h1>
<p></p>
<div id="question" class="tmd-base">
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func main() {
	x := []int{7, 8, 9}
	y := [3]*int{}
	for i, v := range x {
		defer func() {
			print(v)
		}()
		y[i] = &amp;i
	}
	print(*y[0], *y[1], *y[2], " ")
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">012 789</label></li>
<li><label for="choiceB">012 987</label></li>
<li><label for="choiceC">222 789</label></li>
<li><label for="choiceD">222 999</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 222 999 (before Go 1.22), 012 987 (since Go 1.22)
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/fRZCVPt0i8f">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Prior to Go 1.22, the iteration variables (here they are <code class="tmd-code-span">i</code> and <code class="tmd-code-span">v</code>) are shared by all loop steps. In other words, each iteration variable only has one instance during the execution of the loop. That means all the elements of <code class="tmd-code-span">y</code> store the same address (of the value <code class="tmd-code-span">v</code>). In the end, the variable <code class="tmd-code-span">i</code> is set as <code class="tmd-code-span">2</code>, and the variable <code class="tmd-code-span">v</code> is set as <code class="tmd-code-span">9</code>.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
So, prior to Go 1.22, the output is 222 999.
</div>
<p></p>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Since Go 1.22, the iteration variables (here they are <code class="tmd-code-span">i</code> and <code class="tmd-code-span">v</code>) will get new instances at each loop step. So, since Go 1.22, the output is 222 999.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
Different from the above program, the following program always prints <code class="tmd-code-span">012 987</code>, either prior to or since Go 1.22.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func main() {
	x := []int{7, 8, 9}
	y := [3]*int{}
	for i, v := range x {
		defer print(v)
		
		i := i
		y[i] = &amp;i
	}
	print(*y[0], *y[1], *y[2], " ")
}
</code></pre>
<p></p>
</div>
<p></p>
</div>
